package com.uatair.web.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.uatair.common.kafka.domain.protobuf.FlightProto;
import com.uatair.common.mqtt.domain.task.*;
import com.uatair.common.mqtt.uploader.*;
import com.uatair.common.utils.bean.BeanUtils;
import com.uatair.common.utils.uuid.UUID;
import com.uatair.system.domain.*;
import com.uatair.system.domain.vo.TaskVo;
import com.uatair.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component("ZhiBaoYunTask")
public class ZhiBaoYunTask {

    @Autowired
    private ITpPlatformService tpPlatformService;

    @Autowired
    private TpProjectTaskService tpProjectTaskService;

    @Autowired
    private ITpSortieTaskService tpSortieTaskService;

    @Autowired
    private ITpUavTaskService tpUavTaskService;

    @Autowired
    private ITpRecodeService tpRecodeService;

    private final HeNanTaskUploader heNanTaskUploader;

    private final TianJinTaskUploader tianJinTaskUploader;

    public ZhiBaoYunTask(HeNanTaskUploader heNanTaskUploader, TianJinTaskUploader tianJinTaskUploader) {
        this.heNanTaskUploader = heNanTaskUploader;
        this.tianJinTaskUploader = tianJinTaskUploader;
    }

    public void zbyTask() throws ParseException {
        //每天/每小时更新一次值保云项目并同步飞机及架次数据
        ZhiBaoYunTaskUploader zhiBaoYunTaskUploader = new ZhiBaoYunTaskUploader();
        List<Region> regionData = zhiBaoYunTaskUploader.getRegionData(null, 1);
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        for (Region region : regionData) {
            TpPlatform regionPlatform = tpPlatformService.getOne(new QueryWrapper<TpPlatform>().eq("region_id", region.getRegionCode()));
            if (regionPlatform == null) {
                //无该省份平台
                regionPlatform = new TpPlatform();
                regionPlatform.setName(region.getRegionName());
                regionPlatform.setPlatform("暂无对接平台");
                regionPlatform.setRegionId(region.getRegionCode());
                regionPlatform.setPlatformType("1");
                regionPlatform.setStatus("0");
                regionPlatform.setParentId(1L);
                tpPlatformService.save(regionPlatform);
            }
            TaskDetail taskDetail = zhiBaoYunTaskUploader.getTaskDetail(region.getTaskId(), 1);
            if (taskDetail != null) {
                List<AgUav> uavs = taskDetail.getUavs();
                List<AgSortie> agSorties = taskDetail.getAgSorties();
                //同步任务状态
                TpProjectTask task = tpProjectTaskService.getOne(new QueryWrapper<TpProjectTask>().eq("task_id", taskDetail.getTaskId())
                        .eq("platform_id", regionPlatform.getId()));
                if (task != null) {
                    task.setName(taskDetail.getTaskName() + "-" + region.getRegionName());
                    task.setStartDate(sdf1.parse(region.getStartTime()));
                    task.setEndDate(sdf1.parse(region.getEndTime()));
                    task.setPlatformId(regionPlatform.getId());
                    task.setStatus(region.getStatus());
                    if (task.getStartDate().before(date))
                        task.setExecuteStatus("1");
                    if (task.getEndDate().before(date)) {
                        TpSortieTask sortieTask = new TpSortieTask();
                        sortieTask.setTaskId(taskDetail.getTaskId());
                        sortieTask.setPlatformId(regionPlatform.getId());
                        sortieTask.setStatus("0");
                        List<TpSortieTask> getList = tpSortieTaskService.selectTpSortieTaskList(sortieTask);
                        if (getList.isEmpty())
                            task.setExecuteStatus("2");
                    }
                    tpProjectTaskService.updateById(task);
                } else {
                    task = new TpProjectTask();
                    task.setTaskId(taskDetail.getTaskId());
                    task.setName(taskDetail.getTaskName() + "-" + region.getRegionName());
                    task.setStartDate(sdf1.parse(region.getStartTime()));
                    task.setEndDate(sdf1.parse(region.getEndTime()));
                    task.setPlatformId(regionPlatform.getId());
                    task.setStatus(region.getStatus());
                    if (task.getStartDate().before(date))
                        task.setExecuteStatus("1");
                    else
                        task.setExecuteStatus("0");
                    tpProjectTaskService.save(task);
                }
                List<TpUavTask> uavTaskList = new ArrayList<>();
                if (uavs != null) {
                    for (AgUav uav : uavs) {
                        TpUavTask uavTask = tpUavTaskService.getOne(new QueryWrapper<TpUavTask>().eq("task_id", taskDetail.getTaskId())
                                .eq("platform_id", regionPlatform.getId()).eq("sn", uav.getSn()));
                        if (uavTask == null) {
                            uavTask = new TpUavTask();
                            uavTask.setSn(uav.getSn());
                            uavTask.setName(uav.getName());
                            uavTask.setTaskId(taskDetail.getTaskId());
                            uavTask.setPlatformId(regionPlatform.getId());
                            uavTask.setUavType(uav.getUavType());
                            uavTask.setModel(uav.getModel());
                            uavTask.setFactory("LHFJ");
                        }
                        uavTask.setChargeName(uav.getNickname());
                        uavTask.setCodeOfFlightControl(uav.getCodeOfFlightControl());
                        uavTask.setCodeOfBodyFrame(uav.getCodeOfBodyFrame());
                        uavTask.setCodeOfSuit(uav.getCodeOfSuit());
                        uavTask.setCodeOfGroundStation(uav.getCodeOfGroundStation());
                        uavTaskList.add(uavTask);
                    }
                }
                if (!uavTaskList.isEmpty()) {
                    tpUavTaskService.saveOrUpdateBatch(uavTaskList);
                    log.info("任务：{}，id：{}添加成功，无人机共计：{}台，更新成功：{}台", task.getName(), taskDetail.getTaskId(), uavs.size(), uavTaskList.size());
                }
                List<TpSortieTask> sortieTaskList = new ArrayList<>();
                if (agSorties != null) {
                    for (AgSortie agSortie : agSorties) {
                        TpSortieTask sortieTask = tpSortieTaskService.getOne(new QueryWrapper<TpSortieTask>().eq("task_id", taskDetail.getTaskId())
                                .eq("platform_id", regionPlatform.getId()).eq("sortie_no", agSortie.getSortieNo()));
                        if (sortieTask == null) {
                            if (sdf1.parse(region.getStartTime()).before(sdf2.parse(agSortie.getStartTime())) &&
                                    sdf1.parse(region.getEndTime()).after(sdf2.parse(agSortie.getStartTime()))) {
                                sortieTask = new TpSortieTask();
                                sortieTask.setTaskId(taskDetail.getTaskId());
                                sortieTask.setPlatformId(regionPlatform.getId());
                                sortieTask.setSn(agSortie.getSn());
                                sortieTask.setSortieNo(agSortie.getSortieNo());
                                sortieTask.setTeamName(agSortie.getTeamName());
                                sortieTask.setAcreName(agSortie.getAcreName());
                                sortieTask.setFlightDistance(agSortie.getFlightDistance());
                                sortieTask.setFlightTime(agSortie.getFlightTime());
                                sortieTask.setStartTime(sdf2.parse(agSortie.getStartTime()));
                                sortieTask.setEndTime(sdf2.parse(agSortie.getEndTime()));
                                sortieTask.setDosage(agSortie.getDosage());
                                sortieTask.setSize(agSortie.getSize());
                                sortieTask.setNgSize(0d);
                                sortieTask.setGeoJson(agSortie.getGeoJson());
                                sortieTask.setOptMode(agSortie.getOptMode());
                                sortieTask.setDosageOfKg(agSortie.getDosageOfKg());
                                sortieTask.setRouteMode(agSortie.getRouteMode());
                                sortieTask.setPositionInfo(agSortie.getPositionInfo());
                                sortieTask.setFlightSpeed(agSortie.getFlightSpeed());
                                sortieTask.setFlightHeight(agSortie.getFlightHeight());
                                sortieTask.setLineSpacing(agSortie.getLineSpacing());
                                sortieTask.setUsageOfAcre(agSortie.getUsageOfAcre());
                                sortieTask.setPumpSpeed(0d);
                                sortieTask.setPath(agSortie.getUavDataPath());
                                sortieTaskList.add(sortieTask);
                            }
                        }
                    }
                }
                if (!sortieTaskList.isEmpty()) {
                    tpSortieTaskService.saveBatch(sortieTaskList);
                    log.info("任务：{}，id：{}，添加成功，架次共计：{}条，新增：{}条", task.getName(), taskDetail.getTaskId(), agSorties.size(), sortieTaskList.size());
                    if (task.getExecuteStatus().equals("2")) {
                        task.setExecuteStatus("1");
                        tpProjectTaskService.updateById(task);
                    }
                }
            }
        }
    }

    public void projectTask(){
        List<TaskVo> projectTaskVo = tpProjectTaskService.getProjectTaskVo(0);
        List<RecodeTask> recodeTaskList = new ArrayList<>();
        for (TaskVo taskVo : projectTaskVo){
            log.info("统管统治名称：{}，无人机数量：{}，待推送架次：{}",taskVo.getName(),taskVo.getUavTaskList().size(), taskVo.getSortieTaskList().size());
            TaskDTO taskDTO = putTaskDTO(taskVo);
            if (taskVo.getPlatformId() == 2) {
                //苏农云推送 设备：61253722311E
                log.info("苏农云推送");
                SuNongYunTaskUploader suNongYunTaskUploader = new SuNongYunTaskUploader();
                List<RecodeTask> recodeTasks = suNongYunTaskUploader.putSuNongYunTask(taskDTO);
                if (!recodeTasks.isEmpty())
                    recodeTaskList.addAll(recodeTasks);
            } else if (taskVo.getPlatformId() == 3) {
                //湖北推送 设备：612737193106
                log.info("湖北推送");
                HuBeiTaskUploader huBeiTaskUploader = new HuBeiTaskUploader();
                List<RecodeTask> recodeTasks = huBeiTaskUploader.putHuBeiTask(taskDTO);
                if (!recodeTasks.isEmpty())
                    recodeTaskList.addAll(recodeTasks);
            } else if (taskVo.getPlatformId() == 4) {
                //安徽推送 未确定
                log.info("安徽推送");
                AnhuiAgricultureTaskUploader anhuiTaskUploader = new AnhuiAgricultureTaskUploader();
                List<RecodeTask> recodeTasks = anhuiTaskUploader.putAnHuiTask(taskDTO);
                if (!recodeTasks.isEmpty())
                    recodeTaskList.addAll(recodeTasks);
            } else if (taskVo.getPlatformId() == 5) {
                //河南推送 多设备
                log.info("河南推送");
                List<RecodeTask> recodeTasks = heNanTaskUploader.putHeNanTask(taskDTO);
                if (!recodeTasks.isEmpty())
                    recodeTaskList.addAll(recodeTasks);
            } else if (taskVo.getPlatformId() == 8) {
                //天津推送 多设备
                log.info("天津推送");
                List<RecodeTask> recodeTasks = tianJinTaskUploader.putTianJinTask(taskDTO);
                if (!recodeTasks.isEmpty())
                    recodeTaskList.addAll(recodeTasks);
            }  else {
                //未知第三方
                log.info("未知第三方");
            }
            if (!taskVo.getSortieTaskList().isEmpty()){
                List<Long> ids = taskVo.getSortieTaskList().stream().map(TpSortieTask::getId).collect(Collectors.toList());
                //根据id批量修改架次状态为1
                tpSortieTaskService.update(new LambdaUpdateWrapper<TpSortieTask>().in(TpSortieTask::getId, ids).set(TpSortieTask::getStatus, 1) );
            }
        }
        if (!recodeTaskList.isEmpty()) {
            List<TpRecode> recodeList = new ArrayList<>();
            for (RecodeTask recodeTask : recodeTaskList){
                TpRecode tpRecode = new TpRecode();
                BeanUtils.copyProperties(recodeTask, tpRecode);
                recodeList.add(tpRecode);
            }
            tpRecodeService.saveBatch(recodeList);
        }
    }

    //实体复制至TaskDTO
    public TaskDTO putTaskDTO(TaskVo taskVo) {
        TaskDTO taskDTO = new TaskDTO();
        BeanUtils.copyProperties(taskVo, taskDTO);
        if (taskVo.getUavTaskList() != null) {
            List<TpUavTask> tpUavTaskList = taskVo.getUavTaskList();
            List<UavTask> uavTaskList = new ArrayList<>();
            for (TpUavTask uavTask : tpUavTaskList){
                UavTask uavTask1 = new UavTask();
                BeanUtils.copyProperties(uavTask, uavTask1);
                uavTaskList.add(uavTask1);
            }
            taskDTO.setUavTaskList(uavTaskList);
        }
        if (taskVo.getSortieTaskList() != null) {
            List<TpSortieTask> tpSortieTaskList = taskVo.getSortieTaskList();
            List<SortieTask> sortieTaskList = new ArrayList<>();
            for (TpSortieTask  tpSortieTask : tpSortieTaskList){
                SortieTask sortieTask = new SortieTask();
                BeanUtils.copyProperties(tpSortieTask, sortieTask);
                sortieTaskList.add(sortieTask);
                tpSortieTask.setStatus("1");
            }
            taskDTO.setSortieTaskList(sortieTaskList);
        }
        return taskDTO;
    }
}
